const express = require('express');
const { body, validationResult } = require('express-validator');
const { query } = require('../config/database');
const { authenticateToken } = require('../middleware/auth');

const router = express.Router();

// 获取好友列表
router.get('/', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;

    const friends = await query(`
      SELECT 
        u.id,
        u.username,
        u.email,
        u.avatar,
        u.bio,
        u.is_online,
        u.last_seen_at,
        f.status,
        f.created_at as friendship_created_at
      FROM friendships f
      JOIN users u ON f.friend_id = u.id
      WHERE f.user_id = ? AND f.status = 'accepted'
      ORDER BY u.username ASC
    `, [userId]);

    res.json({ success: true, friends });
  } catch (error) {
    console.error('获取好友列表失败:', error);
    res.status(500).json({ success: false, message: '获取好友列表失败' });
  }
});

// 搜索用户
router.get('/search', authenticateToken, async (req, res) => {
  try {
    const { q } = req.query;
    const userId = req.user.id;

    if (!q || q.trim().length < 2) {
      return res.status(400).json({ success: false, message: '搜索关键词至少2个字符' });
    }

    const users = await query(`
      SELECT 
        u.id,
        u.username,
        u.email,
        u.avatar,
        u.bio,
        f.status as friendship_status
      FROM users u
      LEFT JOIN friendships f ON (
        (f.user_id = ? AND f.friend_id = u.id) OR 
        (f.friend_id = ? AND f.user_id = u.id)
      )
      WHERE u.id != ? 
        AND (u.username LIKE ? OR u.email LIKE ?)
      ORDER BY u.username ASC
      LIMIT 20
    `, [userId, userId, userId, `%${q}%`, `%${q}%`]);

    res.json({ success: true, users });
  } catch (error) {
    console.error('搜索用户失败:', error);
    res.status(500).json({ success: false, message: '搜索用户失败' });
  }
});

// 发送好友请求
router.post('/request', authenticateToken, [
  body('friend_id').isInt().withMessage('好友ID必须是整数')
], async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ success: false, message: errors.array()[0].msg });
    }

    const userId = req.user.id;
    const { friend_id } = req.body;

    if (userId === friend_id) {
      return res.status(400).json({ success: false, message: '不能添加自己为好友' });
    }

    // 检查用户是否存在
    const user = await query('SELECT id, username FROM users WHERE id = ?', [friend_id]);
    if (user.length === 0) {
      return res.status(404).json({ success: false, message: '用户不存在' });
    }

    // 检查是否已经是好友或已发送请求
    const existingFriendship = await query(`
      SELECT id, status FROM friendships 
      WHERE (user_id = ? AND friend_id = ?) OR (user_id = ? AND friend_id = ?)
    `, [userId, friend_id, friend_id, userId]);

    if (existingFriendship.length > 0) {
      const friendship = existingFriendship[0];
      if (friendship.status === 'accepted') {
        return res.status(400).json({ success: false, message: '已经是好友了' });
      } else if (friendship.status === 'pending') {
        return res.status(400).json({ success: false, message: '好友请求已发送' });
      } else if (friendship.status === 'blocked') {
        return res.status(400).json({ success: false, message: '该用户已被屏蔽' });
      }
    }

    // 创建好友请求
    await query(`
      INSERT INTO friendships (user_id, friend_id, status) 
      VALUES (?, ?, 'pending')
    `, [userId, friend_id]);

    res.json({ success: true, message: '好友请求已发送' });
  } catch (error) {
    console.error('发送好友请求失败:', error);
    res.status(500).json({ success: false, message: '发送好友请求失败' });
  }
});

// 获取好友请求列表
router.get('/requests', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;

    const requests = await query(`
      SELECT 
        f.id,
        f.status,
        f.created_at,
        u.id as user_id,
        u.username,
        u.email,
        u.avatar,
        u.bio
      FROM friendships f
      JOIN users u ON f.user_id = u.id
      WHERE f.friend_id = ? AND f.status = 'pending'
      ORDER BY f.created_at DESC
    `, [userId]);

    res.json({ success: true, requests });
  } catch (error) {
    console.error('获取好友请求失败:', error);
    res.status(500).json({ success: false, message: '获取好友请求失败' });
  }
});

// 处理好友请求
router.put('/requests/:id', authenticateToken, [
  body('action').isIn(['accept', 'reject']).withMessage('操作必须是accept或reject')
], async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ success: false, message: errors.array()[0].msg });
    }

    const requestId = req.params.id;
    const { action } = req.body;
    const userId = req.user.id;

    // 检查请求是否存在且属于当前用户
    const request = await query(`
      SELECT id, user_id, friend_id, status 
      FROM friendships 
      WHERE id = ? AND friend_id = ? AND status = 'pending'
    `, [requestId, userId]);

    if (request.length === 0) {
      return res.status(404).json({ success: false, message: '好友请求不存在' });
    }

    if (action === 'accept') {
      // 接受好友请求 - 创建双向好友关系
      await query('UPDATE friendships SET status = ? WHERE id = ?', ['accepted', requestId]);
      
      // 创建反向好友关系
      await query(`
        INSERT INTO friendships (user_id, friend_id, status) 
        VALUES (?, ?, 'accepted')
      `, [userId, request[0].user_id]);

      res.json({ success: true, message: '好友请求已接受' });
    } else {
      // 拒绝好友请求
      await query('DELETE FROM friendships WHERE id = ?', [requestId]);
      res.json({ success: true, message: '好友请求已拒绝' });
    }
  } catch (error) {
    console.error('处理好友请求失败:', error);
    res.status(500).json({ success: false, message: '处理好友请求失败' });
  }
});

// 删除好友
router.delete('/:friendId', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const friendId = req.params.friendId;

    // 删除双向好友关系
    await query(`
      DELETE FROM friendships 
      WHERE (user_id = ? AND friend_id = ?) OR (user_id = ? AND friend_id = ?)
    `, [userId, friendId, friendId, userId]);

    res.json({ success: true, message: '好友已删除' });
  } catch (error) {
    console.error('删除好友失败:', error);
    res.status(500).json({ success: false, message: '删除好友失败' });
  }
});

// 屏蔽用户
router.post('/block', authenticateToken, [
  body('friend_id').isInt().withMessage('好友ID必须是整数')
], async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ success: false, message: errors.array()[0].msg });
    }

    const userId = req.user.id;
    const { friend_id } = req.body;

    // 更新或创建屏蔽关系
    await query(`
      INSERT INTO friendships (user_id, friend_id, status) 
      VALUES (?, ?, 'blocked')
      ON DUPLICATE KEY UPDATE status = 'blocked'
    `, [userId, friend_id]);

    res.json({ success: true, message: '用户已屏蔽' });
  } catch (error) {
    console.error('屏蔽用户失败:', error);
    res.status(500).json({ success: false, message: '屏蔽用户失败' });
  }
});

// 更新用户在线状态
router.post('/online-status', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const { is_online } = req.body;

    await query(`
      UPDATE users 
      SET is_online = ?, last_seen_at = NOW() 
      WHERE id = ?
    `, [is_online, userId]);

    res.json({ success: true, message: '在线状态更新成功' });
  } catch (error) {
    console.error('更新在线状态失败:', error);
    res.status(500).json({ success: false, message: '更新在线状态失败' });
  }
});

module.exports = router;
